package leetcode;

import java.util.Map;
import java.util.TreeMap;

/**
 * @author yinlei
 * @date 2018/7/16
 * @since 1.0.0
 */
public class N731MyCalendarII {

    public static void main(String[] args) {
//        TreeMap<Integer, Integer> map = new TreeMap<>();
//
//        map.put(10, 1);
//        map.put(1, 10);
//
//        System.out.println(map);
    }

    static class MyCalendarTwo {

        TreeMap<Integer, Integer> cal = new TreeMap<>();

        public MyCalendarTwo() {

        }

        public boolean book(int start, int end) {

            getNAdd(cal, start);
            getNMinus(cal, end);

            int c = 0;

            for (Map.Entry<Integer, Integer> item : cal.entrySet()) {
                c += item.getValue();
                if (c > 2) {
                    getNMinus(cal, start);
                    getNAdd(cal, end);
                    return false;
                }
            }

            return true;
        }

        private void getNMinus(TreeMap<Integer,Integer> cal, int end) {
            Integer count = cal.get(end);
            if (count == null) {
                count = 0;
            }
            cal.put(end, count - 1);
        }

        private void getNAdd(TreeMap<Integer,Integer> cal, int start) {
            Integer count = cal.get(start);
            if (count == null) {
                count = 0;
            }
            cal.put(start, count + 1);
        }
    }
}
